import { initParticlesJS } from '../particles.js'

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function () {
    //粒子效果
    initParticlesJS();

    // 检查用户登录状态并更新界面
    updateUserInterface();

    // 加载论坛板块
    loadForumSections();

    // 加载热门帖子
    loadHotPosts();

    // 加载最新帖子
    loadLatestPosts();

    // 设置发布新帖功能
    setupPostFunctionality();

    // 设置正在开发中的功能
    setupDevelopmentFeatures();

    // 移动菜单切换
    document.getElementById('mobile-menu-btn').addEventListener('click', function () {
        const mobileMenu = document.getElementById('mobile-menu');
        if (mobileMenu.classList.contains('hidden')) {
            mobileMenu.classList.remove('hidden');
        } else {
            mobileMenu.classList.add('hidden');
        }
    });
});

// 更新用户界面
function updateUserInterface() {
    const user = localStorage.getItem('currentUser') ? JSON.parse(localStorage.getItem('currentUser')) : null;
    const authSection = document.getElementById('user-auth-section');
    const infoSection = document.getElementById('user-info-section');

    if (user) {
        authSection.classList.add('hidden');
        infoSection.classList.remove('hidden');
        document.getElementById('username').textContent = user.username;
        document.getElementById('user-avatar').src = user.avatar || 'https://picsum.photos/40/40';

        // 退出登录
        document.getElementById('logout-btn').addEventListener('click', function () {
            localStorage.removeItem('currentUser');
            window.location.reload();
        });
    } else {
        authSection.classList.remove('hidden');
        infoSection.classList.add('hidden');
    }

    // 更新购物车数量
    updateCartCount();
}

// 更新购物车数量
function updateCartCount() {
    const cart = localStorage.getItem('cart') ? JSON.parse(localStorage.getItem('cart')) : [];
    const cartCount = document.getElementById('cart-count');
    cartCount.textContent = cart.length;
}

// 加载论坛板块
async function loadForumSections() {
    const sectionsContainer = document.getElementById('forum-sections');

    const response = await fetch('http://localhost:3000/api/getAllPlate', {
        method: 'Get',
        headers: { 'Content-Type': 'application/json' }
    });

    if (!response.ok) {
        throw new Error('网络请求失败');
    }

    // 解析响应数据
    const responseData = await response.json();

    // 提取 data 字段作为板块数据
    const sections = responseData.data;

    // 检查 sections 是否为数组
    if (!Array.isArray(sections)) {
        console.error('从服务器返回的数据不是数组:', sections);
        return;
    }

    // 清空容器
    sectionsContainer.innerHTML = '';

    // 添加板块
    sections.forEach(section => {
        const sectionElement = document.createElement('div');
        sectionElement.className = 'bg-white rounded-lg shadow-md overflow-hidden hover:shadow-xl transition duration-300 transform hover:-translate-y-1';
        // 修改关键：将 href 从 "forum.html" 改为 "forumInfo.html"，并传递板块ID
        sectionElement.innerHTML = `
            <a href="forumInfo.html?section=${section.plateId}"> 
                <img src="/assets/bgs/bankuai.png?${section.plateName}" alt="${section.plateName}" class="w-full h-40 object-cover">
                <div class="p-5">
                    <div class="flex items-center mb-3">
                        <div class="bg-blue-100 text-blue-600 w-10 h-10 rounded-full flex items-center justify-center mr-3">
                            <i class="fas fa-fishing-rod"></i>
                        </div>
                        <h3 class="text-xl font-bold">${section.plateName}</h3>
                    </div>
                    <p class="text-gray-600 mb-4">${section.plateDescription}</p>
                    <div class="flex justify-between text-sm text-gray-500">
                        <span><i class="fas fa-users mr-1"></i> 0 成员</span>
                        <span><i class="fas fa-comments mr-1"></i> 0 帖子</span>
                    </div>
                </div>
            </a>
        `;
        sectionsContainer.appendChild(sectionElement);
    });
}

// 加载热门帖子
async function loadHotPosts() {
    const postsContainer = document.getElementById('hot-posts');

    // 加载后端数据热门
    const response = await fetch('http://localhost:3000/api/hotPost', {
        method: 'GET',
        headers: { 'Content-Type': 'application/json' }
    });

    if (!response.ok) {
        throw new Error('网络请求失败');
    }

    // 解析响应数据
    const responseData = await response.json();

    // 提取 data 字段作为帖子数据，根据后端返回的结构修改为正确的字段
    const posts = responseData.data;

    // 检查 posts 是否为数组
    if (!Array.isArray(posts)) {
        console.error('从服务器返回的数据不是数组:', posts);
        return;
    }

    // 清空容器
    postsContainer.innerHTML = '';

    // 添加帖子
    posts.forEach(post => {
        const postElement = document.createElement('div');
        postElement.className = 'p-4 hover:bg-gray-50 transition';
        postElement.innerHTML = `
            <div class="flex items-start">
                <div class="flex-shrink-0 mr-4">
                    <div class="bg-blue-100 text-blue-600 w-10 h-10 rounded-full flex items-center justify-center">
                        <i class="fas fa-fire"></i>
                    </div>
                </div>
                <div class="flex-1 min-w-0">
                    <h3 class="text-lg font-medium text-gray-900 mb-1">
                         <a href="post.html?id=${post.postId}" class="text-lg font-medium text-gray-900 hover:text-blue-600 transition-colors">${post.title}</a>
                    </h3>
                    <div class="flex flex-wrap items-center text-sm text-gray-500">
                        <span class="mr-3"><i class="fas fa-user mr-1"></i>${post.user ? post.user.nickname : '未知用户'}</span>
                        <span class="mr-3"><i class="far fa-clock mr-1"></i>${post.createTime}</span>
                        <span class="mr-3"><i class="fas fa-tag mr-1"></i>板块: ${post.plate.plateName}</span>
                    </div>
                </div>
                <div class="ml-4 flex flex-col items-end">
                    <div class="flex space-x-4 text-sm text-gray-500">
                        <span><i class="far fa-thumbs-up mr-1"></i>${post.likeCount}</span>
                        <span><i class="far fa-comment mr-1"></i>${post.commentCount}</span>
                        <!-- 后端未提供 views 字段，这里暂时显示为 0 -->
                        <span><i class="far fa-eye mr-1"></i>0</span>
                    </div>
                </div>
            </div>
        `;
        postsContainer.appendChild(postElement);
    });
}

// 加载最新帖子
function loadLatestPosts() {
    const postsContainer = document.getElementById('latest-posts');

    // 模拟帖子数据
    const posts = [
        {
            id: 4,
            title: "活动通知：本周日江边垂钓聚会",
            author: "活动组织者",
            date: "2025-05-04",
            likes: 29,
            comments: 22,
            views: 187,
            section: "社区活动"
        },
        {
            id: 5,
            title: "请教：如何选择适合的鱼线？",
            author: "钓鱼小白",
            date: "2025-05-05",
            likes: 14,
            comments: 18,
            views: 120,
            section: "装备讨论"
        },
        {
            id: 6,
            title: "经验分享：夜钓的注意事项",
            author: "夜钓达人",
            date: "2025-05-06",
            likes: 31,
            comments: 9,
            views: 145,
            section: "钓技研究"
        },
        {
            id: 7,
            title: "今日收获：3斤重的鲤鱼",
            author: "快乐钓鱼人",
            date: "2025-05-06",
            likes: 42,
            comments: 15,
            views: 230,
            section: "淡水钓鱼"
        }
    ];

    // 清空容器
    postsContainer.innerHTML = '';

    // 添加帖子
    posts.forEach(post => {
        const postElement = document.createElement('div');
        postElement.className = 'p-4 hover:bg-gray-50 transition';
        postElement.innerHTML = `
                    <div class="flex items-start">
                        <div class="flex-shrink-0 mr-4">
                            <img src="https://picsum.photos/40/40?user=${post.id}" alt="${post.author}" class="w-10 h-10 rounded-full">
                        </div>
                        <div class="flex-1 min-w-0">
                            <h3 class="text-lg font-medium text-gray-900 mb-1">
                                <a href="post.html?id=${post.id}" class="hover:text-blue-600">${post.title}</a>
                            </h3>
                            <div class="flex flex-wrap items-center text-sm text-gray-500">
                                <span class="mr-3"><i class="fas fa-user mr-1"></i>${post.author}</span>
                                <span class="mr-3"><i class="far fa-clock mr-1"></i>${post.date}</span>
                                <span class="mr-3"><i class="fas fa-tag mr-1"></i>${post.section}</span>
                            </div>
                        </div>
                        <div class="ml-4 flex flex-col items-end">
                            <div class="flex space-x-4 text-sm text-gray-500">
                                <span><i class="far fa-thumbs-up mr-1"></i>${post.likes}</span>
                                <span><i class="far fa-comment mr-1"></i>${post.comments}</span>
                                <span><i class="far fa-eye mr-1"></i>${post.views}</span>
                            </div>
                        </div>
                    </div>
                `;
        postsContainer.appendChild(postElement);
    });
}

// 设置发布新帖功能
function setupPostFunctionality() {
    const newPostBtn = document.getElementById('new-post-btn');
    const postModal = document.getElementById('post-modal');
    const closePostModal = document.getElementById('close-post-modal');
    const cancelPost = document.getElementById('cancel-post');
    const newPostForm = document.getElementById('new-post-form');

    newPostBtn.addEventListener('click', function () {
        const user = localStorage.getItem('currentUser') ? JSON.parse(localStorage.getItem('currentUser')) : null;

        if (!user) {
            window.location.href = 'auth.html';
            return;
        }

        postModal.classList.remove('hidden');
    });

    closePostModal.addEventListener('click', function () {
        postModal.classList.add('hidden');
    });

    cancelPost.addEventListener('click', function () {
        postModal.classList.add('hidden');
    });

    newPostForm.addEventListener('submit', function (e) {
        e.preventDefault();

        const title = document.getElementById('post-title').value.trim();
        const section = document.getElementById('post-section').value;
        const content = document.getElementById('post-content').value.trim();
        const user = JSON.parse(localStorage.getItem('currentUser'));

        if (!title || !section || !content) {
            return;
        }

        // 获取现有帖子
        let posts = JSON.parse(localStorage.getItem('forumPosts') || '[]');

        // 创建新帖子
        const newPost = {
            id: Date.now().toString(),
            title: title,
            content: content,
            author: user.username,
            authorAvatar: user.avatar,
            date: new Date().toISOString(),
            section: section,
            likes: 0,
            comments: [],
            views: 0
        };

        // 添加到帖子列表
        posts.unshift(newPost);

        // 保存到localStorage
        localStorage.setItem('forumPosts', JSON.stringify(posts));

        // 关闭模态框
        postModal.classList.add('hidden');

        // 重置表单
        newPostForm.reset();

        // 重新加载最新帖子
        loadLatestPosts();

        // 显示成功通知
        showNotification('帖子发布成功！');
    });
}

// 设置正在开发中的功能
function setupDevelopmentFeatures() {
    const devFeatureButtons = [
        document.getElementById('communityBtn'),
        document.getElementById('techniqueBtn')
    ];

    const devModal = document.getElementById('development-modal');
    const closeDevModal = document.getElementById('close-dev-modal');

    devFeatureButtons.forEach(button => {
        if (button) {
            button.addEventListener('click', function (e) {
                e.preventDefault();
                devModal.classList.remove('hidden');
            });
        }
    });

    closeDevModal.addEventListener('click', function () {
        devModal.classList.add('hidden');
    });
}

// 显示通知
function showNotification(message) {
    const notification = document.createElement('div');
    notification.className = 'fixed bottom-4 right-4 bg-green-500 text-white p-4 rounded-lg shadow-lg z-50';
    notification.textContent = message;
    document.body.appendChild(notification);

    setTimeout(() => {
        notification.classList.add('opacity-0', 'transition-opacity', 'duration-300');
        setTimeout(() => {
            notification.remove();
        }, 300);
    }, 2000);
}